package com.banyiyi.simple.juc;

import jdk.internal.org.objectweb.asm.Handle;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @ClassName CompletableFutureDemo
 * @Description TODO
 * @Author yangwm
 * @Date 2023/3/22 15:34
 * @Version 1.0
 */
public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        // 获取当前系统种cpu个数
        int i = Runtime.getRuntime().availableProcessors();

        // 无返回值
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("hello world"), Executors.newFixedThreadPool(Integer.valueOf(i)));
        future1.get();

        // 有返回值
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello Mr.shu");
        System.out.println(future2.get());


//        Random rand = new Random();
//        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
//            try {
//                Thread.sleep(1000 + rand.nextInt(1000));
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } finally {
//                System.out.println("future1 done...");
//            }
//            return "abc";
//        });
//        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
//            try {
//                Thread.sleep(1000 + rand.nextInt(1000));
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } finally {
//                System.out.println("future2 done...");
//            }
//            return "efg";
//        });

        // 合并执行多个
//        CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
//        completableFuture.join();

//        CompletableFuture<String> completableFuture
//                = CompletableFuture.supplyAsync(() -> "hello!")
//                .thenCombine(CompletableFuture.supplyAsync(
//                        () -> " world!"), (s1, s2) -> s1 + s2)
//                .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " nice!"));
//        System.out.println(completableFuture.get(1000, TimeUnit.MILLISECONDS));

    }
}
